package algorithm.leetcode.I201to400;

import algorithm.leetcode.I201to400.NestedInteger;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


public class Q341{

}

class NestedIterator implements Iterator<Integer> {

    List<Integer> list = new ArrayList<>();
    int index = -1; // 迭代器索引要从-1开始,否则第一个数拿不到

    public NestedIterator(List<NestedInteger> nestedList) {
        for (NestedInteger nestedInteger : nestedList) {
            flatten(nestedInteger);
        }
    }

    @Override
    public Integer next() {
        return list.get(index);
    }

    @Override
    public boolean hasNext() {
        // ++在前,先加一,再判断
        return ++index < list.size();
    }

    private void flatten(NestedInteger n) {
        if (n.isInteger()) list.add(n.getInteger());
        else {
            List<NestedInteger> tempList = n.getList();
            for (NestedInteger nn : tempList) {
                flatten(nn);
            }
        }
    }
}

